/**
 * express 配置文件
 */
'use strict';
import path from 'path';
import db from './mongodb/db';
import express from 'express';
import session from 'express-session';
import connectMongo from 'connect-mongo';
import flash from 'connect-flash';
import config from 'config-lite';
import routes from './routes/index';
import cookieParser from 'cookie-parser';
import winston from 'winston';
import expressWinston from 'express-winston';
import history from 'connect-history-api-fallback';
import pkg from './package.json';

const app = express();
const configInfo = config(path.join(__dirname, 'config'));

//设置响应头
app.all('*', (req, res, next) => {
	res.header("Access-Control-Allow-Origin", req.headers.origin || '*');
	res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With");
	res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
	res.header("Access-Control-Allow-Credentials", true); //可以带cookies
	res.header("X-Powered-By", '3.2.1');
	if(req.method == 'OPTIONS') {
		res.send(200);
	} else {
		next();
	}
});

// 设置模板目录
app.set('views', path.join(__dirname, 'views'));
// 设置模板引擎为 ejs
app.set('view engine', 'ejs')

// session 中间件
const MongoStore = connectMongo(session);
app.use(cookieParser());
app.use(session({
	name: configInfo.session.name, // 设置 cookie 中保存 session id 的字段名称
	secret: configInfo.session.secret, // 通过设置 secret 来计算 hash 值并放在 cookie 中， 使产生的 signedCookie 防篡改
	resave: true, // 强制更新 session
	saveUninitialized: false, // 设置为 false, 强制创建一个 session, 即使用户未登录
	cookie: configInfo.session.cookie, // 过期时间，过期后 cookie 中的 session id 自动删除
	store: new MongoStore({ // 将 session 存储到 mongodb
		url: configInfo.mongodb // mongodb 地址
	})
}));

// flash 中间件， 用来显示通知
app.use(flash());

// 设置模板全局常量
app.locals.description = {
	title: pkg.name,
	description: pkg.description
};

// 添加模板必需的三个变量
app.use((req, res, next) => {
	res.locals.username = req.session.username;
	res.locals.success = req.flash('success').toString();
	res.locals.error = req.flash('error').toString();
	next();
});

// 正常请求的日志
app.use(expressWinston.logger({
	transports: [
		new (winston.transports.Console)({
			json: true,
			colorize: true
		}),
		new winston.transports.File({
			filename: './logs/success.log'
		})
	]
}));

// 路由
routes(app);
// 错误请求的日志
app.use(expressWinston.errorLogger({
	transports: [
		new winston.transports.Console({
			json: true,
			colorize: true
		}),
		new winston.transports.File({
			filename: './logs/error.log'
		})
	]
}));

// error 页面
app.use((err, req, res, next) => {
	res.render('error', {
		error: err
	});
});

app.use(history());
app.use(express.static(path.join(__dirname, 'public')));
app.listen(configInfo.port, () => {
	console.log(`${pkg.name} listening on port ${configInfo.port}`);
});



